<template>
  <div class="picture-list">
    <div class="masonry-grid">
      <div
        v-for="picture in dataList"
        :key="picture.id"
        class="picture-card"
        :class="{ 'long-image': isLongImage(picture) }"
        @click="handlePictureClick(picture)"
      >
        <div class="user-info">
          <img
            :src="picture.user?.userAvatar || '/default-avatar.png'"
            class="user-avatar"
            alt="user avatar"
          />
          <span class="user-name">{{ picture.user?.userName || '未知用户' }}</span>
        </div>
        <img
          :src="picture.url"
          :alt="picture.name || '图片'"
          class="picture-image"
          loading="lazy"
          @error="handleImageError"
        />
        <div class="picture-stats">
          <div class="stat-item">
            <EyeOutlined />
            <span>{{ formatCount(picture.viewNum) }}</span>
          </div>
          <div class="stat-item">
            <LikeOutlined />
            <span>{{ formatCount(picture.thumbNum) }}</span>
          </div>
          <div class="stat-item">
            <MessageOutlined />
            <span>{{ formatCount(picture.favourNum) }}</span>
          </div>
        </div>
      </div>
    </div>
    <div v-if="loading" class="loading-container">
      <a-spin size="large" />
    </div>
    <ShareModal ref="shareModalRef" :link="shareLink" />
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import {
  EyeOutlined,
  LikeOutlined,
  MessageOutlined,
} from '@ant-design/icons-vue'
import { deletePictureUsingPost } from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import ShareModal from '@/components/ShareModal.vue'
import { ref } from 'vue'

interface Props {
  dataList?: API.PictureVO[]
  loading?: boolean
  showOp?: boolean
  canEdit?: boolean
  canDelete?: boolean
  onReload?: () => void
}

const props = withDefaults(defineProps<Props>(), {
  dataList: () => [],
  loading: false,
  showOp: false,
  canEdit: false,
  canDelete: false,
})

const router = useRouter()

// 判断是否为长图片
const isLongImage = (picture: any) => {
  if (!picture.picHeight || !picture.picWidth) return false
  return picture.picHeight / picture.picWidth > 1.8 // 高宽比大于1.8的判定为长图
}

// 点击图片跳转到详情页
const handlePictureClick = (picture: any) => {
  router.push(`/picture/${picture.id}`)
}

// 图片加载错误处理
const handleImageError = (e: Event) => {
  const target = e.target as HTMLImageElement
  target.src = '/placeholder-image.png' // 替换为默认占位图
}

// 搜索
const doSearch = (picture, e) => {
  // 阻止冒泡
  e.stopPropagation()
  // 打开新的页面
  window.open(`/search_picture?pictureId=${picture.id}`)
}

// 编辑
const doEdit = (picture, e) => {
  // 阻止冒泡
  e.stopPropagation()
  // 跳转时一定要携带 spaceId
  router.push({
    path: '/add_picture',
    query: {
      id: picture.id,
      spaceId: picture.spaceId,
    },
  })
}

// 删除数据
const doDelete = async (picture, e) => {
  // 阻止冒泡
  e.stopPropagation()
  const id = picture.id
  if (!id) {
    return
  }
  const res = await deletePictureUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    props.onReload?.()
  } else {
    message.error('删除失败')
  }
}

// ----- 分享操作 ----
const shareModalRef = ref()
// 分享链接
const shareLink = ref<string>()
// 分享
const doShare = (picture, e) => {
  // 阻止冒泡
  e.stopPropagation()
  shareLink.value = `${window.location.protocol}//${window.location.host}/picture/${picture.id}`
  if (shareModalRef.value) {
    shareModalRef.value.openModal()
  }
}

// 格式化数字显示（大于1000显示为1k+）
const formatCount = (count: number | undefined) => {
  if (!count) return '0'
  return count > 999 ? (count / 1000).toFixed(1) + 'k' : count
}
</script>

<style scoped>
.picture-list {
  width: 100%;
  min-height: calc(100vh - 300px); /* 确保内容区域有最小高度 */
  position: relative;
}

.masonry-grid {
  columns: 4;
  column-gap: 16px;
  width: 100%;
}

@media (max-width: 1200px) {
  .masonry-grid {
    columns: 3;
  }
}

@media (max-width: 768px) {
  .masonry-grid {
    columns: 2;
  }
}

@media (max-width: 480px) {
  .masonry-grid {
    columns: 1;
  }
}

.picture-card {
  break-inside: avoid;
  margin-bottom: 16px;
  position: relative;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.picture-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
}

.user-info {
  position: absolute;
  top: 12px;
  left: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(255, 255, 255, 0.9);
  padding: 6px 12px;
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 1;
}

.user-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid rgba(255, 255, 255, 0.6);
}

.user-name {
  font-size: 12px;
  color: #333;
  max-width: 100px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.picture-image {
  width: 100%;
  display: block;
  max-height: 70vh; /* 从80vh减小到70vh，限制最大高度 */
  object-fit: cover;
  border-radius: 12px;
}

.loading-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

/* 添加图片加载动画 */
.picture-image {
  opacity: 0;
  animation: fadeIn 0.3s ease forwards;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* 对于特别长的图片添加渐变遮罩 */
.picture-card.long-image:after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100px;
  background: linear-gradient(to bottom, transparent, rgba(0, 0, 0, 0.5));
  border-radius: 0 0 12px 12px;
}

/* 图片统计信息 */
.picture-stats {
  position: absolute;
  bottom: 10px;
  right: 10px;
  display: flex;
  gap: 12px;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
  padding: 6px 12px;
  border-radius: 20px;
  z-index: 2;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: white;
  font-size: 12px;
}

.stat-item .anticon {
  font-size: 14px;
}
</style>
